//
//  HMRemind.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/8/9.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import FSCalendar
import SwiftyJSON
// FSCalendarAppearance：用于全局外观属性的定制。
//FSCalendarDelegateAppearance：针对某天外观属性的定制
class HMRemind: HMViewController, FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance {
    
    
    var configJson: JSON?
    var reminderJson = JSON()
    let calendar:FSCalendar = FSCalendar()
    let chineseCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.chinese)!
    let typeViewContainer = UIView()
    let list = HMRemindList()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "日历"
        self.view.backgroundColor = configure.shareConfigure.HMColor2
        
        
        let configDic = NSDictionary.init(contentsOfFile: NSHomeDirectory() + "/Library/Caches/config.plist")
        self.configJson = JSON.init(configDic as Any)
//        self.configJson = NSMutableArray.init(contentsOfFile: NSHomeDirectory() + "/Library/Caches/drugs.plist")
        //ary.write(toFile: file, atomically: true)
        
    }
    
    override func setupView() {

        view.addSubview(calendar)
        view.addSubview(typeViewContainer)
        view.addSubview(list.tableView)
        
        calendar.frame = CGRect(x: 0, y: 0, width: view.wWidth, height: 280)
        calendar.dataSource = self
        calendar.delegate = self;
        calendar.appearance.headerDateFormat = "yyyy年MM月" //年月格式
//        calendar.allowsMultipleSelection = false;  //支持多选
        calendar.appearance.caseOptions = FSCalendarCaseOptions(rawValue: FSCalendarCaseOptions.weekdayUsesSingleUpperCase.rawValue)
        calendar.appearance.headerMinimumDissolvedAlpha = 0 //设置上个，下个透明
        calendar.appearance.eventDefaultColor = UIColor.red  //
        calendar.select(Date()) //// 设置默认选中日期是今天
        let locale: NSLocale = NSLocale(localeIdentifier: "zh_CN") //设置为中文
        calendar.locale = locale as Locale
        calendar.backgroundColor = UIColor.white
//        calendar.scrollDirection = .vertical //垂直切换
//        calendar.appearance.weekdayTextColor = UIColor.gray //星期颜色
        calendar.appearance.subtitleTodayColor = UIColor.green
        calendar.appearance.subtitleDefaultColor = UIColor.blue
        calendar.clipsToBounds = true
        calendar.scope = .month
//        calendar.scope = .week  //
        calendar.placeholderType = FSCalendarPlaceholderType.fillHeadTail //FSCalendarPlaceholderTypeFillHeadTail
        calendar.contentView.addLayer(isAddLayer: (false, false, false, true), color: UIColor.red, crude: 1, layout: (w: view.wWidth, h: 301))
//
        
//        typeViewContainer.frame = CGRect(x: 0, y: calendar.frame.maxY, width: view.wWidth, height: 80)
        typeViewContainer.topVertically(view: calendar, predicate: "10")
        typeViewContainer.leadingAlign(view: view, predicate: "0")
        typeViewContainer.trailingAlign(view: view, predicate: "0")
        typeViewContainer.heightConstrain(predicate: "80")
        

        let sub2 = UIButton()
        typeViewContainer.addSubview(sub2)
       
        
        sub2.centerXYAlign(view: typeViewContainer)
        sub2.backgroundColor = configure.shareConfigure.HMColor1
        sub2.leadingAlign(view: view, predicate: "30")
        sub2.trailingAlign(view: view, predicate: "-30")
        sub2.setTitle("添加提醒事项", for: .normal)
        sub2.layer.cornerRadius = 8
        sub2.heightConstrain(predicate: "50")
        sub2.addTarget(self, action: #selector(subClick), for: UIControlEvents.touchUpInside)
        

        typeViewContainer.backgroundColor = UIColor.white
        
        list.tableView.topVertically(view: typeViewContainer, predicate: "10")
        list.tableView.leadingAlign(view: view, predicate: "0")
        list.tableView.trailingAlign(view: view, predicate: "0")
        list.tableView.bottomAlign(view: view,predicate: "0")
        list.delegate = self
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    @objc func subClick(sender: UIButton) { // 添加提醒事项
        
        
        
        let matter = HMRemindMatter()
//           matter.configData = self.configJson
        var dat = JSON.init([[
                "id": "5bba1833d8b51e8af721cf6b",
                "userId": "5b616c555ce1e09be399aedf",
                "medicineName": "111",
                "timesOneDay": 2,
                "reminderTime": [
                "4:33",
                "14:00"
                ],
                "takeTime": 1,
                "dosage": 3,
                "dosageUnit": 1,
                "treatment": 2,
                "intervalMode": 1,
                "intervalTemplate": 3, //1
              //  "weekTemplate": 0, // 1
                "remark": "sedflkj",
                "startTime": "2018-10-07T14:31:52.000+0000",
                "endTime": "2018-10-19T04:18:32.000+0000",
                "createdTime": "2018-10-07T14:29:07.085+0000",
                "updateTime": "2018-10-07T14:29:07.085+0000"
            ]
            ])
        
        matter.reminderJson =  dat //self.list.reminderJson
        matter.inletName = "提醒"
        matter.selecotDate = Date.stringToTimeStamp(stringTime: "2019-02-14 00:00:00") + "000"
        self.pushViewController(matter, animated: true)
    }
    
    
    // 多行布局
    func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
        UIView.animate(withDuration: 0.3, animations: {
              self.calendar.frame = CGRect(origin: calendar.frame.origin,size: bounds.size)
        }) { (isTrue) in
            
        }
        
        print("0---%f",calendar.frame.origin.y);
        print("0---%f",self.list.tableView.frame.origin.y);
        
//        self.view.layoutIfNeeded()
    }
    
    
    
    // 选择的内容
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        
//        let timeZone = TimeZone(identifier: "UTC")
//        formatter.timeZone = timeZone
       let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh_CN")
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        let dateString = formatter.string(from: date)
//        let strDate = dateString.components(separatedBy: " ").first!
        print("---->\(dateString)")
      
        
        
        
    }
    
    func calendar(_ calendar: FSCalendar, didDeselect date: Date, at monthPosition: FSCalendarMonthPosition) {
        print("取消---->\(date)")
    }
    // 翻页时
    func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
        print("----->>x\(calendar.currentPage)")
    }
    
    func calendar(_ calendar: FSCalendar, hasEventFor date: Date) -> Bool {
        
        if date == Date.init() {
            return true
        }
        
        return false
    }
    
    
    //设置当前月与非当前月字体颜色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? {
       
        // 日历获取到的日期
       let str = Date.getFromString(date: date)
       let index = str?.index((str?.startIndex)!, offsetBy: 7)
       let dateStr = String(describing: str?.prefix(upTo: index!))
        
        // 当前日期
       let currentDateStr = Date.getCurrentDate()
        let currentStr = String(describing: currentDateStr?.prefix(upTo: index!))
       
        if dateStr == currentStr {
            return UIColor.green
        }else {
            return nil
        }
    }
    
    
    
    // 设置可选日期
    func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool {
//        print("---设置可以选的日期\(date)-----\(monthPosition.rawValue)")
        
        // 日历获取到的日期
        let str = Date.getFromString(date: date)
        let index = str?.index((str?.startIndex)!, offsetBy: 7)
        let index2 = str?.index((str?.startIndex)!, offsetBy: 8)
//        let datePrefixStr = String(describing: str?.prefix(upTo: index!))
//        let dateSuffixStr = (str?.suffix(from: index2!)) as? Int
        
        
        let currentDateStr = Date.getCurrentDate()
//        let currentStr = String(describing: currentDateStr?.prefix(upTo: index!))
        
        return true
        
    }
    

    
    
    // MARK: - mark FSCalendarDelegateAppearance
//    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? {
//        //设置当前月与非当前月字体颜色
//        if calendar.
//    }
//
    
    
    
    
    //日期设置副标题
//    func calendar(_ calendar: FSCalendar, subtitleFor date: Date) -> String? {
//
//    }
    // 修改标题
//    func calendar(_ calendar: FSCalendar, titleFor date: Date) -> String? {
//
//        print("---->\(date)") //calendar.isDate(inRange: date)
//        if(calendar.isDate(inToday: date)) { //[calendar isDateInToday:date]
//            return "今天";
//        }
//        return  nil //date as String
//    }
    
    
    //- (nullable NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date;
    
    func calendar(_ calendar: FSCalendar, subtitleFor date: Date) -> String? {
         print("----快看看\(date)")
        
        //        let lunarDay = chineseCalendar.component(NSCalendar.Unit.day, from: date as Date)
        //        let lunarChars: [String] = ["初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二一", "二二", "二三", "二四", "二五", "二六", "二七", "二八", "二九", "三十"]
        //        let lunarDayString = lunarChars[]
        if(calendar.isDate(inToday: date)) {
            return "今天"
        }
        
        return nil
    }

    private func calendar(_ calendar: FSCalendar!, imageFor date: NSDate!) -> UIImage! {

        let anyImage = UIImage(named: "qq.png") // UIImage.init(named: "disease.png")
        return anyImage
    }
     // 事件 对有事件的显示一个点,默认是显示三个点
//    func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
//
////        let dateFormatter:NSDateFormatter =  //DateFormatter()
////        dateFormatter.dateFormat = @"yyyy-MM-dd";
////        if ([self.datesWithEvent containsObject:[dateFormatter stringFromDate:date]]) {
////            return 1;
////        }
////
//        return 1
//    }

    
}


//HMRemindListDelegate
extension HMRemind : HMRemindListDelegate {
    func remindList(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
           let matter = HMRemindMatter() //进入详情
           self.pushViewController(matter, animated: true)
    }
    
    
}


